<template>
  <div>
      <!-- 面包屑导航 -->
     <el-breadcrumb separator-class="el-icon-arrow-right">
       <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
       <el-breadcrumb-item>商品管理</el-breadcrumb-item>
       <el-breadcrumb-item>商品分类</el-breadcrumb-item>
     </el-breadcrumb>
     
     <el-card>
        <el-row>
          <el-col :span="4">
            <el-button type="primary" @click="addcategories">添加分类</el-button>
          </el-col>
        </el-row>
        <!-- 渲染分类列表 -->
         <table-tree :data="categorylist" :selection-type="false" border :expand-type="false" :show-index="true" :columns="columns">
            <template slot="isok" slot-scope="scope">
               <i class="el-icon-success" v-if="scope.row.cat_deleted===true" style="color:green"></i>
               <i class="el-icon-error" v-else style="color:green"></i>
            </template>
            <template slot="sort" slot-scope="scope">
               <el-tag v-if="scope.row.cat_level===0" type="success">0 级</el-tag>
               <el-tag v-else-if="scope.row.cat_level===1" type="success">一级</el-tag>
               <el-tag v-else>二级</el-tag>
            </template>
            <template slot="operate" slot-scope="scope">
                <el-button size="mini" @click="removecategory(scope.row)" type="danger">删除</el-button>
                <el-button size="mini" @click="editcategory(scope.row)" type="primary">编辑</el-button>
            </template>
         </table-tree>
         
         <!-- 分页功能 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[1, 3, 5, 8]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>

         <!-- 编辑分类弹出框 -->
        <el-dialog title="编辑分类" :visible.sync="editcategoriesvisable" width="50%"
               :before-close="handleClose">
            <!-- 区域 -->
             <el-form :model="editcategoryuserinfo" status-icon :rules="categoryrules"
                ref="editcategoryrule" label-width="100px">
                 <el-form-item label="分类名称" prop="cat_name">
                   <el-input v-model="editcategoryuserinfo.cat_name"></el-input>
                 </el-form-item>
             </el-form>
            <template slot="footer" class="dialog-footer">
              <el-button @click="removeeditcategoryform">取 消</el-button>
              <el-button @click="determineeditputin" type="primary">确 定</el-button>
            </template>
       </el-dialog>

         <!-- 添加分类弹出框 -->
        <el-dialog title="添加分类" :visible.sync="addcategoriesvisable" width="50%"
               :before-close="handleClose">
            <!-- 区域 -->
             <el-form :model="addcategoryuserinfo" status-icon :rules="categoryrules"
                ref="categoryrule" label-width="100px">
                 <el-form-item label="分类名称" prop="cat_name">
                   <el-input v-model="addcategoryuserinfo.cat_name"></el-input>
                 </el-form-item>
                 <el-form-item label="父级分类">
                    <el-cascader v-model="selectvalue" :options="options" clearable change-on-select
                     :props="optionvalue" @change="handleChange">
                    </el-cascader>
                 </el-form-item>
             </el-form>
            <template slot="footer" class="dialog-footer">
              <el-button @click="removecategoryform">取 消</el-button>
              <el-button @click="determineputin" type="primary">确 定</el-button>
            </template>
       </el-dialog>

     </el-card>

  </div>
</template>

<script>
export default {
   name:'Category',
   data(){
       return{
        //  查询条件
          queryInfo:{
            type:3,
            pagenum:1,
            pagesize:5
          },
          // 分页信息total总数
          total:0,
          addcategoriesvisable:false,
          editcategoriesvisable:false,
          // 需要数据
          categorylist:[],
          // 添加商品分类表单数据
          addcategoryuserinfo:{
            cat_pid:'0',
            cat_name:'',
            cat_level:'0'
          },
          // 编辑分类表单数据
          editcategoryuserinfo:{
            cat_name:''
          },
          // 权限树列数据
          columns:[{
            label:'分类名称',
            prop:'cat_name'
          },{
            label:'是否有效',
            type:'template',
            // 指定template插槽名
            template:'isok'
          },{
            label:'排序',
            // prop:'cat_level'
            type:'template',
            template:'sort'
          },{
            label:'操作栏',
            type:'template',
            // 指定template插槽名
            template:'operate'
          }],
          // 下拉框数据源
          options:[],
          // 指定级联配置
          optionvalue:{
            label:'cat_name',
            value:'cat_id',
            children:'children'
          },
          // 保存下拉框选中数据项
          selectvalue:[],
          // 添加分类验证规则
          categoryrules:{
            cat_name:[
                { required: true, message: '请输入分类名', trigger: 'blur' },
                {min: 2,max: 10,message: '分类名的长度在2～10个字',trigger: 'blur'}
              ]
          }
       }
   },
   methods:{
     async getcategorylist(){
         const {data:res}=await this.$http.get('categories',{params:this.queryInfo})
         if(res.meta.status!=200){return this.$message('获取失败')}
         this.categorylist=res.data.result
         this.total=res.data.total
     },
    //  点击添加商品分类
     async addcategories(){
        this.addcategoriesvisable=true
        const {data:res}=await this.$http.get('categories',{params:{type:2}})
        if(res.meta.status!=200){return this.$message('获取失败')}
        this.options=res.data
        
     },
     // 点击x 关闭前的回调，会暂停 Dialog 的关闭
    handleClose(done){
       this.$confirm('确认关闭？')
          .then(_ => { done() })
          .catch(_ => {});
    },
    // 删除当前分类接口
     removecategory(row){
      this.$confirm('确认关闭？')
          .then(async() => { 
            const{data:res}=await this.$http.delete(`categories/${row.cat_id}`)
            if(res.meta.status!=200){return this.$message('删除失败')}
            this.$message.success(res.meta.msg)
            this.getcategorylist()
            })
          .catch(() => {});
     },
    //  点击编辑分类
     editcategory(row){
       this.editcategoryuserinfo=row
       this.editcategoriesvisable=true
     },
    //  取消编辑分类对话框
    removeeditcategoryform(){
      this.$refs.editcategoryrule.resetFields()
      this.editcategoriesvisable=false
    },
    //  确定修改编辑分类
    determineeditputin(){
      this.$refs.editcategoryrule.validate(async valid => {
        if(!valid){return this.$message.error('验证错误')}
        const {data:res}=await this.$http.put(`categories/${this.editcategoryuserinfo.cat_id}`,this.editcategoryuserinfo)
        if(res.meta.status!=200){return this.$message.error('修改错误')}
        this.$message.success(res.meta.msg)
        this.getcategorylist()
      })
      this.$refs.editcategoryrule.resetFields()
      this.editcategoriesvisable=false
    },
    //  取消添加分类弹框
    removecategoryform(){
      this.$refs.categoryrule.resetFields()
      this.addcategoryuserinfo={}
      this.selectvalue=[]
      this.addcategoriesvisable=false
    },
    // 确定添加分类列表
    async determineputin(){
      const {data:res}=await this.$http.post('categories',this.addcategoryuserinfo)
      if(res.meta.status!==201){return this.$message('添加失败')}
      this.$message.success(res.meta.msg)
      console.log(this.addcategoryuserinfo);
      this.$refs.categoryrule.resetFields()
      this.addcategoriesvisable=false
    },
    // pageSize 改变时会触发
    handleSizeChange(pagesize){
        this.queryInfo.pagesize=pagesize
        this.getcategorylist()
    },
    // currentPage 当前页改变时会触发
    handleCurrentChange(pagenum){
        this.queryInfo.pagenum=pagenum
        this.getcategorylist()
    },
    // 下拉框选中触发
    handleChange(value){
      console.log(this.selectvalue);
      if(this.selectvalue.length>0){
        this.addcategoryuserinfo.cat_pid=this.selectvalue[this.selectvalue.length-1]
        this.addcategoryuserinfo.cat_level=this.selectvalue.length
        return 
      }else{
        this.addcategoryuserinfo.cat_pid=0
        this.addcategoryuserinfo.cat_level=0
      }
    }
   },
   created(){
     this.getcategorylist()
   }
}
</script>

<style lang="less" scoped>
  .el-card{
    margin-top: 20px;
  }
</style>